<?php
class User extends CI_Controller {
	
	function User (){
		parent::__construct();
		$this->load->model(array('disability_model', 'leadership_model', 'buddyType_model', 'user_model', 'club_model', 'employee_model'));
	}
	
	public function signUp()
	{
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('lastname', 'Lastname', 'required');
		$this->form_validation->set_rules('ci', 'Ci', 'required');
		$this->form_validation->set_rules('genre', 'Genre', 'required');
		$this->form_validation->set_rules('birthdate', 'Birthdate', 'required');
		$this->form_validation->set_rules('buddy_type', 'Buddy_type', 'callback_buddyType_check');
		$this->form_validation->set_rules('id_club', 'Id_club', 'callback_club_check');
		$this->form_validation->set_rules('celphone', 'Celphone', 'required');
		$this->form_validation->set_rules('phone', 'phone', 'required');
		$this->form_validation->set_rules('address', 'Address', 'required');
		$this->form_validation->set_rules('country', 'Country', 'required');
		$this->form_validation->set_rules('state', 'State', 'required');
		$this->form_validation->set_rules('municipality', 'Municipality', 'required');
		$this->form_validation->set_rules('avenue', 'Avenue', 'required');
		$this->form_validation->set_rules('street', 'Street', 'required');
		$this->form_validation->set_rules('parish', 'Parish', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		
		/*Optional Fields:
		$this->form_validation->set_rules('twitter', 'Twitter', 'required');
		$this->form_validation->set_rules('facebook', 'Facebook', 'required');
		$this->form_validation->set_rules('webpage', 'Webpage', 'required');
		$this->form_validation->set_rules('disability', 'Disability', 'required');
		$this->form_validation->set_rules('id_buddy', 'Id_buddy', 'required');*/
		
		$this->form_validation->set_rules('password', 'Password', 'required|matches[passwordConf]|md5');
		$this->form_validation->set_rules('passwordConf', 'PasswordConf', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['disabilities'] = $this->disability_model->get_actives();	
			$data['buddy_types'] = $this->buddyType_model->get_actives();	
			$data['buddies'] = $this->user_model->all();	
			$data['clubs'] = $this->club_model->all();	
			
					
			$this->load->view('user/signUp', $data);
		}
		else
		{
			$data ['ci_integrante'] = $_POST["ci"];
			$data ['nombre'] = $_POST["name"];
			$data ['apellido'] = $_POST["lastname"];
			$data ['genero'] = $_POST["genre"];
			$data ['fecha_nacimiento'] = change2ymd($_POST["birthdate"]);
			$data ['fecha_inscripcion'] = date('Y-m-d');
			$data ['direccion'] = $_POST["address"];
			$data ['calle'] = $_POST["street"];
			$data ['avenida'] = $_POST["avenue"];
			$data ['parroquia'] = $_POST["parish"];
			$data ['municipio'] = $_POST["municipality"];
			$data ['estado'] = $_POST["state"];
			$data ['pais'] = $_POST["country"];
			$data ['telefono_celular'] = $_POST["celphone"];
			$data ['telefono_habitacion'] = $_POST["phone"];
			$data ['email'] = $_POST["email"];
			$data ['twitter'] = $_POST["twitter"];
			$data ['facebook'] = $_POST["facebook"];
			$data ['pag_web'] = $_POST["webpage"];
			$data ['COD_TIPO_BUDDY'] = $_POST["buddy_type"];
			
			if($_POST["disability"] != '-')
				$data ['COD_DISCAPACIDAD'] = $_POST["disability"];
			else
				$data ['COD_DISCAPACIDAD'] = NULL;
				
			$data ['condicion'] = 'pendiente';
			$data ['ID_CLUB'] = $_POST["id_club"];
			$data ['password'] = $_POST["password"];
			
			//If the new member has an assigned buddy.
			if($_POST["id_buddy"] != ''){
				$leadership_levels = $this->leadership_model->find('Miembro Asociado con Buddy', 'descripcion');
				
				$data ['ID_BEST_BUDDY'] = $_POST["id_buddy"];
				$data ['COD_POS_LIDERAZGO'] = $leadership_levels[0]['cod_pos_liderazgo'];
			}
			else if($_POST["id_buddy"] == ''){
				$leadership_levels = $this->leadership_model->find('Miembro Asociado sin Buddy', 'descripcion');
				
				$data ['ID_BEST_BUDDY'] = NULL;
				$data ['COD_POS_LIDERAZGO'] = $leadership_levels[0]['cod_pos_liderazgo'];
			}
	
			$this->user_model->insert($data);	
			
			$params = array();
			$params['view'] = "emails/new_user";
			$params['data']['date'] = date('d/m/Y');
			$params['data']['user'] = $data ['nombre'].' '.$data ['apellido'].', CI: '.$data ['ci_integrante']; 
			$foundation = $this->employee_model->get_foundation();
			$params['from'] = $foundation['0']['correo_corporativo'];
			$params['name'] = $foundation['0']['nombre_envio_correo'];
			$params['to'] = $foundation['0']['correo_recibo_de_información'];
			$params['subject'] = "Nuevo Integrante Registrado";
			send_email($params);			
			
			$data['message'] = 'Integrante pendiende, en espera por aprobaci&oacute;n';
			$this->load->view('home', $data);		
		}
	}
	
	function buddyType_check($str)
	{
		if ($str == '-')
		{
			$this->form_validation->set_message('buddyType_check', 'Debe seleccionar un valor v&aacute;lido');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function club_check($str)
	{
		if ($str == '-')
		{
			$this->form_validation->set_message('club_check', 'Debe seleccionar un valor v&aacute;lido');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function check_user($return){
		$this->load->helper('security');
		
		$email = $_POST["email"];
		$password = do_hash($_POST["password"],'md5');
		
		$user = $this->user_model->login($email, $password);
		
		if(count($user) > 0){
			if($user[0]['condicion'] == 'activo'){
				if($return == 'string')
					echo 'success';
				else
					return $user[0];
				}
			else{
				echo 'error2';
			}
		}
		else{
			echo 'error1';
		}
	}
	
	function login(){
		$user = $this->check_user('object');
		$this->session->set_userdata($user);
		$data['message'] = NULL;
		$this->load->view('home', $data);
	}
	
	function sign_out(){
		$this->session->sess_destroy();
		$this->session->unset_userdata('id_integrante');
		$this->session->unset_userdata('COD_POS_LIDERAZGO');
		$this->session->unset_userdata('ID_BEST_BUDDY');
		$data['message'] = NULL;
		$this->load->view('home', $data);
	}
	
	function lostPassword(){
		$this->form_validation->set_rules('lostEmail', 'LostEmail', 'required|valid_email|callback_lostEmail_check');
		
		$this->form_validation->set_error_delimiters('<div align="center" class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('user/lost_password');
		}
		else
		{
			$user = $this->user_model->find('email', $_POST["lostEmail"]);
			$user = $user[0];
			$new_password = '';
			for($i=0; $i < 6; $i++){
				$new_password .= rand(0, 9);
			}
			$this->load->helper('security');
			$update = array('password' => do_hash($new_password,'md5'));
			$this->user_model->update($user['id_integrante'], $update);
			$data['date'] = date('d/m/Y');
			$data['user'] = $user;
			$data['new_password'] = $new_password;
			//$this->load->view('emails/recovery_information', $data);
			$params = array();
			$params['view'] = "emails/recovery_information";
			$params['data'] = $data;
			$foundation = $this->employee_model->get_foundation();
			$params['from'] = $foundation['0']['correo_corporativo'];
			$params['name'] = $foundation['0']['nombre_envio_correo'];
			$params['to'] = $_POST["lostEmail"];
			$params['subject'] = "Recuperacion de informacion";
			send_email($params);
			
			$msg['msg'] = "Un correo electronico ha sido enviado a su direccion de correo con la informacion necesaria para acceder al sitio";
			$this->load->view('user/lost_password');
		}
	}
	
	function lostEmail_check($str)
	{
		$user = $this->user_model->find('email', $str);
		if (count($user) == 0)
		{
			$this->form_validation->set_message('lostEmail_check', 'Direcci&oacute;n de correo electr&oacute;nico no almacenada en sistema');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function profile(){
		if($this->session->userdata('id_integrante')){
			$data['user'] = $this->user_model->find('id_integrante', $this->session->userdata('id_integrante'));
			$data['user'] = $data['user'][0];
			if($data['user']['COD_DISCAPACIDAD'] != NULL){
				$data['user']['discapacidad_descripcion'] = $this->disability_model->find($data['user']['COD_DISCAPACIDAD']);
				$data['user']['discapacidad_descripcion'] = $data['user']['discapacidad_descripcion'][0]['descripcion'];
			}
			if($data['user']['ID_BEST_BUDDY'] != NULL){
				$data['user']['BUDDY'] = $this->user_model->find('id_integrante', $data['user']['ID_BEST_BUDDY']);
				$data['user']['BUDDY'] = $data['user']['BUDDY'][0];
			}
			$this->load->view('user/profile', $data);
		}
		else{
			$this->load->helper('url');
			redirect('/home/denied');
		}
	}
	
	function edit_profile(){
		if($this->session->userdata('id_integrante')){
			$this->form_validation->set_rules('name', 'Name', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('ci', 'Ci', 'required');
			$this->form_validation->set_rules('genre', 'Genre', 'required');
			$this->form_validation->set_rules('birthdate', 'Birthdate', 'required');
			$this->form_validation->set_rules('buddy_type', 'Buddy_type', 'callback_buddyType_check');
			$this->form_validation->set_rules('id_club', 'Id_club', 'callback_club_check');
			$this->form_validation->set_rules('celphone', 'Celphone', 'required');
			$this->form_validation->set_rules('parish', 'Parish', 'required');
			$this->form_validation->set_rules('address', 'Address', 'required');
			$this->form_validation->set_rules('country', 'Country', 'required');
			$this->form_validation->set_rules('state', 'State', 'required');
			$this->form_validation->set_rules('municipality', 'Municipality', 'required');
			$this->form_validation->set_rules('avenue', 'Avenue', 'required');
			$this->form_validation->set_rules('street', 'Street', 'required');
			$this->form_validation->set_rules('parish', 'Parish', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');		
			/*$this->form_validation->set_rules('password', 'Password', 'required|matches[passwordConf]|md5');
			$this->form_validation->set_rules('passwordConf', 'PasswordConf', 'required');*/
			
			$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
			
			if ($this->form_validation->run() == FALSE)
			{
				$data['disabilities'] = $this->disability_model->get_actives();	
				$data['buddy_types'] = $this->buddyType_model->get_actives();	
				$data['buddies'] = $this->user_model->all();	
				$data['clubs'] = $this->club_model->all();	
				
				$data['user'] = $this->user_model->find("id_integrante", $this->session->userdata('id_integrante'));
				$data['user'] = $data['user'][0];
				$data['user']['BEST_BUDDY'] = '';
				if($data['user']['ID_BEST_BUDDY']){
					$data['user']['BEST_BUDDY'] = $this->user_model->find("id_integrante", $data['user']['ID_BEST_BUDDY']);
					$data['user']['BEST_BUDDY'] = $data['user']['BEST_BUDDY'][0]['nombre'].' '.$data['user']['BEST_BUDDY'][0]['apellido'].', CI: '.$data['user']['BEST_BUDDY'][0]['ci_integrante'];
				}
				if($data['user']['COD_DISCAPACIDAD']){
					$data['user']['DISCAPACIDAD'] = $this->disability_model->find($data['user']['COD_DISCAPACIDAD']);
					$data['user']['DISCAPACIDAD'] = $data['user']['DISCAPACIDAD'][0]['descripcion'];
				}
				$this->load->view('user/edit', $data);
			}
			else
			{
				$data ['ci_integrante'] = $_POST["ci"];
				$data ['nombre'] = $_POST["name"];
				$data ['apellido'] = $_POST["lastname"];
				$data ['genero'] = $_POST["genre"];
				$data ['fecha_nacimiento'] = change2ymd($_POST["birthdate"]);
				$data ['direccion'] = $_POST["address"];
				$data ['calle'] = $_POST["street"];
				$data ['avenida'] = $_POST["avenue"];
				$data ['parroquia'] = $_POST["parish"];
				$data ['municipio'] = $_POST["municipality"];
				$data ['estado'] = $_POST["state"];
				$data ['pais'] = $_POST["country"];
				$data ['telefono_celular'] = $_POST["celphone"];
				$data ['telefono_habitacion'] = $_POST["phone"];
				$data ['email'] = $_POST["email"];
				$data ['twitter'] = $_POST["twitter"];
				$data ['facebook'] = $_POST["facebook"];
				$data ['pag_web'] = $_POST["webpage"];
				$data ['COD_TIPO_BUDDY'] = $_POST["buddy_type"];
				
				if($_POST["disability"] != '-')
					$data ['COD_DISCAPACIDAD'] = $_POST["disability"];
				else
					$data ['COD_DISCAPACIDAD'] = NULL;
					
				$data ['ID_CLUB'] = $_POST["id_club"];
				//$data ['password'] = $_POST["password"];
				
				if($_POST["id_buddy"] != '')
					$data ['ID_BEST_BUDDY'] = $_POST["id_buddy"];
				else if($_POST["id_buddy"] == '')
					$data ['ID_BEST_BUDDY'] = NULL;
		
				$this->user_model->update($this->session->userdata('id_integrante'), $data);
				$user = $this->user_model->find("id_integrante", $this->session->userdata('id_integrante'));
				$this->session->set_userdata($user[0]);		
				$this->profile();
			}
		}
		else{
			$this->load->helper('url');
			redirect('/home/denied');
		}
	}
	
	function change_password(){
		if($this->session->userdata('id_integrante')){
			$this->form_validation->set_rules('password', 'Password', 'required|matches[passwordConf]|md5');
			$this->form_validation->set_rules('passwordConf', 'PasswordConf', 'required');
			$this->form_validation->set_rules('currentPassword', 'CurrentPassword', 'required|callback_currentPassword_check');
			
			$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
			
			if ($this->form_validation->run() == FALSE)
			{
				$this->load->view('user/change_password');
			}
			else{
				$data['password'] = $_POST["password"];
				$this->user_model->update($this->session->userdata('id_integrante'), $data);
				
				$user = $this->user_model->find("id_integrante", $this->session->userdata('id_integrante'));
				$this->session->set_userdata($user[0]);	
				
				$msg['msg'] = "Clave cambiada exitosamente";
				$this->load->view('user/change_password', $msg);
			}
		}
		else{
			$this->load->helper('url');
			redirect('/home/denied');
		}
	}
	
	function currentPassword_check($str)
	{
		$this->load->helper('security');
		$str = do_hash($str,'md5');
		
		if (strcmp($str,$this->session->userdata('password')) != 0)
		{
			$this->form_validation->set_message('currentPassword_check', 'Contrase&ntilde;a actual incorrecta');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
}
?>











